package com.smqj.icu;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ResourceBundle;

public class ParameterUtil {

    private static Logger logger = LogManager.getLogger(ParameterUtil.class.getName());

    private static String DB_NAME = ResourceBundle.getBundle("icu").getString("db.name");

    public static void setParameter(String key, String value) {
        Connection conn = null;
        PreparedStatement pstm = null;
        SqlLink sqlLink = new SqlLink();


        try {
            conn = sqlLink.getConnection();
            // 执行sql语句
            String querySql = "SELECT count(1) FROM " + DB_NAME + "icu_import_params where \"KEY\" = ?;";
            String insertSql = "INSERT INTO " + DB_NAME + "icu_import_params (\"VALUE\", \"KEY\") VALUES(?, ?);";
            String updateSql = "UPDATE " + DB_NAME + "icu_import_params SET \"VALUE\"=? WHERE \"KEY\"=?;";
            pstm = conn.prepareStatement(querySql);
            pstm.setString(1, key);
            ResultSet rs = pstm.executeQuery();
            int count = 0;
            while (rs.next()) {
                count = rs.getInt(1);
            }
            pstm = conn.prepareStatement(count > 0 ? updateSql : insertSql);
            pstm.setString(1, value.replaceAll("\\\\\\\\", "/").replaceAll("\\\\", "/").replaceAll("//", "/"));
            pstm.setString(2, key);
            pstm.executeUpdate();
            logger.info("设置参数" + key + "成功。");
        } catch (SQLException | ClassNotFoundException e) {
            sqlLink.closeConnection(pstm, conn);
            logger.info("设置参数" + key + "失败。");
            e.printStackTrace();
        } finally {
            sqlLink.closeConnection(pstm, conn);
        }
    }

    public static String getParameter(String key) {
        Connection conn = null;
        PreparedStatement pstm = null;
        String result = null;
        SqlLink sqlLink = new SqlLink();
        try {
            logger.info("开始查询参数：" + key);
            conn = sqlLink.getConnection();
            // 执行sql语句
            String querySql = "SELECT \"VALUE\" FROM " + DB_NAME + "icu_import_params where \"KEY\" = ?;";
            pstm = conn.prepareStatement(querySql);
            pstm.setString(1, key);
            ResultSet rs = pstm.executeQuery();
            while (rs.next()) {
                result = rs.getString(1);
                logger.info("查询成功，结果值为：" + result);
            }
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            sqlLink.closeConnection(pstm, conn);
            return result;
        }
    }

}
